<template>
  <el-container :style="backStyle">
    <el-header height="30px">
      <div class="logo-container" v-if="!showTenant">
        <i
          :class="
            isIeExplorer
              ? 'icon-hotent-H icon-hotent-H-ie'
              : 'icon-hotent-H icon-hotent-H-c'
          "
        />
        <span class="pre-word">O</span>
        <span class="tail-word">TENT</span>
        <el-divider class="logo-divider" direction="vertical"></el-divider>
        <span class="system-name">{{ name }}</span>
      </div>
      <div class="logo-container" v-if="showTenant">
        <a class="logo-link" v-if="showLogo">
          <img :src="logo" style="margin-top: 0; height: 48px" />
        </a>
        <i
          :class="
            isIeExplorer
              ? 'icon-hotent-H icon-hotent-H-ie'
              : 'icon-hotent-H icon-hotent-H-c'
          "
          v-if="!showLogo"
        />
        <span class="pre-word" v-if="!showLogo">O</span>
        <span class="tail-word" v-if="!showLogo">TENT</span>
        <el-divider class="logo-divider" direction="vertical"></el-divider>
        <span class="system-name">{{ companyName }}</span>
      </div>
      <div class="site-div">
        <a href="http://www.hotent.com" tabindex="-1">
          <i class="icon-guanwang"></i>宏天官网
        </a>
      </div>
    </el-header>
    <el-main>
      <div class="login-card__container fullheight">
        <el-card shadow="always" class="login-card">
          <div :style="totemStyle" class="totem-div"></div>
          <div class="login-div">
            <el-form
              style="margin: 20px"
              :model="principal"
              :rules="rules"
              ref="principal"
              v-if="!isTwoStepVerify"
            >
              <div class="welcome-title">欢迎登录</div>
              <el-form-item prop="account">
                <el-input
                  size="medium"
                  clearable
                  prefix-icon="icon-account"
                  v-model="principal.account"
                ></el-input>
              </el-form-item>
              <el-form-item prop="password">
                <el-input
                  show-password
                  clearable
                  prefix-icon="icon-password"
                  @keyup.enter.native="submitForm('principal')"
                  @focus="inputGetFocus"
                  @copy.native.capture.prevent="handlePaste"
                  size="medium"
                  v-model="principal.password"
                ></el-input>
              </el-form-item>
              <el-form-item
                v-if="isShowVerificationCode"
                prop="verificationCode"
              >
                <el-input
                  v-model.trim="principal.verificationCode"
                  tabindex="3"
                  size="large"
                  clearable
                  placeholder="请输入验证码"
                >
                  <div @click="flushVerCode" slot="append">
                    <img :src="captchaImage" class="ver-code" />
                  </div>
                </el-input>
              </el-form-item>

              <!--              <el-alert v-if="responseError" :title="responseError" type="error" :closable="false"></el-alert>-->
              <el-form-item style="text-align: center; margin-top: 10px">
                <el-button
                  size="medium"
                  type="primary"
                  @focus="inputGetFocus"
                  @click="submitForm('principal')"
                  :loading="loading"
                  >登录</el-button
                >
                <el-button
                  size="medium"
                  @click="resetForm('principal')"
                  :disabled="loading"
                  >重置</el-button
                >
              </el-form-item>
            </el-form>
          </div>
        </el-card>
      </div>
    </el-main>
    <el-footer class="copyright"
      >Copyright © 版权所有 宏天软件 {{ new Date().getFullYear() }}</el-footer
    >
  </el-container>
</template>

<script>
import uc from '@/api/uc.js'
import auth from '@/api/auth'
import menu from '@/api/menu'
import {mapState} from 'vuex'
export default {
  name: 'login',
  props: ['tenant'],
  data() {
    var checkAccount = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('请输入账号'))
      }
      if (/^[\u4E00-\u9FA5a-zA-Z0-9_-]{2,20}$/.test(value)) {
        return callback()
      } else {
        return callback(new Error('账号格式不符合规范'))
      }
    }
    const validateVerificationCode = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入验证码'))
      } else {
        callback()
      }
    }
    return {
      logo: '',
      name: '自动排课',
      showTenant: false,
      showLogo: false,
      companyName: '',
      tenantName: '',
      principal: {
        tenantId: '',
        account: '',
        password: '',
        verificationCode: '',
        verificationKey: ''
      },
      rules: {
        account: [{validator: checkAccount, trigger: 'blur'}],
        password: [{required: true, message: '请输入密码', trigger: 'blur'}],
        verificationCode: [
          {required: true, trigger: 'blur', validator: validateVerificationCode}
        ]
      },
      responseError: '',
      loading: false,
      backStyle: {
        width: '100%',
        background: `url(${require('@/assets/img/back.jpg')}) center / 100% auto no-repeat`
      },
      totemStyle: {
        width: '300px',
        height: '320px',
        float: 'left',
        background: `#1975FF url(${require('@/assets/img/totem.png')}) center / 100% auto no-repeat`
      },
      isIeExplorer: false,
      isShowVerificationCode: false,
      captchaImage: '',
      verKey: '',
      code: '',
      isTwoStepVerify: false
    }
  },
  computed: {
    ...mapState('login', ['loginValue', 'loginStatus'])
  },
  watch: {
    isShowVerificationCode(val) {
      if (val) {
        this.$nextTick(() => {
          //获取二维码图片
          this.flushVerCode()
        })
      }
    }
  },
  mounted() {
  },
  methods: {
    flushVerCode() {
      //获取二维码图片
      auth.getCaptcha().then(response => {
        if (response && response.data) {
          this.verKey = response.data.key
          this.captchaImage = response.data.image
        }
      })
    },
    // 禁止复制
    handlePaste() {},
    handleSelect(item) {
      this.tenantName = item.name
      this.principal.tenantId = item.id
    },
    setRouterPath() {
      this.$store.dispatch('login/actionLoginAccount', this.principal.account)
      localStorage.setItem(
        this.principal.account + 'loginRoutePath',
        this.$route.path
      )
    },
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.inputGetFocus()
          this.loading = true
          this.setRouterPath()
          this.principal.verificationKey = this.verKey
          this.$store
            .dispatch('login/loginByPrincipal', this.principal)
            .then(user => {
              this.loading = false
              let {loginStatus, errorCode} = user
              if (errorCode && errorCode === '4012') {
                if (this.isShowVerificationCode) {
                  this.flushVerCode()
                }
                this.isShowVerificationCode = true
                return
              } else if (errorCode && errorCode === '2001') {
                this.isTwoStepVerify = true
                return
              } else if (errorCode && errorCode === '2002') {
                localStorage.setItem('loginData', JSON.stringify(user.value))
                this.$router.push({
                  name: 'security',
                  query: {
                    isTwoStepVerifyAndBind: true
                  }
                })
                return
              }
              let hasMenu = false

              if (this.$route.query.redirect) {
                let alias = this.$route.query.redirect.replace('/', '')
                //预览 是本地路由  else 动态路由判断用户权限
                if (alias.substr(0, 15) == 'templatePreview') {
                  this.routerFrom(loginStatus, true)
                } else {
                    menu.getMenuByAlias(alias).then(res => {
                    if (res && res.state && res.value) {
                      hasMenu = true
                    }
                    this.routerFrom(loginStatus, hasMenu)
                  })
                }
              } else {
                this.routerFrom(loginStatus, hasMenu)
              }
            })
            .catch(msg => {
              this.loading = false
              if (msg.startsWith('timeout of')) {
                msg = '登录超时'
              }
              this.responseError = msg
            })
        } else {
          return false
        }
      })
    },
    routerFrom(loginStatus, hasMenu) {
      if (loginStatus && loginStatus == true) {
        this.$store.dispatch('menu/actionMenus').then(data => {
          this.$router.push({
            path:
              this.$route.query.redirect && hasMenu
                ? this.$route.query.redirect
                : '/'
          })
        })
      } else if (loginStatus == false) {
        this.$router.push({
          name: 'resetPwdView',
          params: {account: this.principal.account}
        })
      }
    },
    inputGetFocus() {
      this.responseError = ''
    },
    resetForm(formName) {
      this.responseError = ''
      this.$refs[formName].resetFields()
    },
  },
  created() {
    let USER_AGENT = navigator.userAgent.toLowerCase()
    let isChrome = /.*(chrome)\/([\w.]+).*/
    if (!isChrome.test(USER_AGENT)) {
      this.isIeExplorer = true
    }
  },
  components: {}
}
</script>
<style lang="scss" scoped>
@import '@/assets/css/element-variables.scss';

.login-card__container {
  display: -webkit-box;
  display: -moz-box;
  display: -ms-flexbox;
  display: -o-box;
  display: box;
  display: -webkit-flex; /* Safari */
  display: flex;
  justify-content: center;
  -webkit-box-align: center;
  -webkit-align-items: center;
  -ms-flex-align: center;
  align-items: center;
}

.logo-container {
  margin-top: 10px;
  display: inline-block;
  margin-left: 30px;
}

.logo-container > i.icon-hotent-H-c {
  font-size: 36px;
  background-image: linear-gradient($--color-secondary, $--color-primary);
  background-clip: text;
  -webkit-background-clip: text;
  color: transparent;
  margin-right: -5px;
}

.logo-container > i.icon-hotent-H-ie {
  font-size: 36px;
  background-clip: text;
  -webkit-background-clip: text;
  color: $--color-primary;
  margin-right: -5px;
}

.logo-container:hover > i.icon-hotent-H-c {
  background-image: linear-gradient($--color-primary, $--color-secondary);
}

.logo-container > span.pre-word {
  font-size: 26px;
  font-weight: bold;
  color: $--color-primary;
}

.logo-container > span.tail-word {
  font-size: 24px;
  font-weight: bold;
  color: #bdbfc2;
}

.logo-container > .logo-divider {
  margin: 0 25px 11px 25px;
  height: 18px;
}

.logo-container > .system-name {
  color: #666;
  font-weight: bold;
  font-size: 16px;
}

.site-div {
  float: right;

  margin-top: 25px;
  margin-right: 40px;
}

.site-div > a {
  color: #5b9dff;
  font-size: 12px;
  text-decoration: none;
}

.site-div > a > i {
  font-weight: bold;
  margin-right: 5px;
}

.login-card {
  width: 600px;
  height: 320px;
}

.totem-div {
  -moz-box-shadow: 2px 2px 5px #999;
  -webkit-box-shadow: 2px 2px 5px #999;
  box-shadow: 2px 2px 5px #999;
}

.login-div {
  width: 300px;
  height: 320px;
  float: right;

  .ver-code {
    width: 80px;
    height: 38px;
    cursor: pointer;
  }
}

.welcome-title {
  margin-top: 40px;
  font-size: 18px;
  margin-bottom: 20px;
}

.copyright {
  color: #999;
  font-size: 13px;
  text-align: center;
}

>>> .el-card__body {
  padding: 0;
}

.login-card /deep/ .el-alert__content {
  padding: 5px;
}

.el-main {
  display: flex;
  justify-content: center;
  align-items: center;
}
.twoStepVerify-box {
  margin: 50px 20px 0 20px;
  .tips {
    margin-top: 12px;
    font-weight: 400;
    line-height: 20px;
    color: #999999;
    font-size: 14px;
  }
  .twoStepVerify-input {
    width: 250px;
  }
}
.twoStepVerify-btn {
  margin-top: 20px;
  width: 150px;
}
</style>
